{% extends "base.html" %}

{% block title %}数据导入 - IT课程数据分析系统{% endblock %}

{% block extra_css %}
<style>
    .import-section {
        margin-bottom: 2rem;
    }
    
    .upload-area {
        border: 2px dashed #3498db;
        border-radius: 8px;
        padding: 2rem;
        text-align: center;
        background: #f8f9fa;
        cursor: pointer;
        transition: all 0.3s;
    }
    
    .upload-area:hover {
        background: #e8f4f8;
        border-color: #2980b9;
    }
    
    .upload-area.dragging {
        background: #d4edda;
        border-color: #28a745;
    }
    
    .upload-icon {
        font-size: 3rem;
        color: #3498db;
        margin-bottom: 1rem;
    }
    
    .file-input {
        display: none;
    }
    
    /* 批量导入样式 */
    .batch-mode {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-color: #667eea;
    }
    
    .batch-mode .upload-icon {
        color: white;
    }
    
    .file-list {
        margin-top: 1rem;
        padding: 1rem;
        background: #f8f9fa;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
    }
    
    .file-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.5rem;
        margin: 0.25rem 0;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
    }
    
    .file-info {
        flex: 1;
        font-size: 0.9rem;
    }
    
    .file-size {
        color: #7f8c8d;
        font-size: 0.8rem;
        margin-left: 0.5rem;
    }
    
    .remove-file {
        background: #e74c3c;
        color: white;
        border: none;
        border-radius: 50%;
        width: 24px;
        height: 24px;
        cursor: pointer;
        font-size: 0.8rem;
    }
    
    .batch-controls {
        margin-top: 1rem;
        text-align: center;
    }
    
    .batch-toggle {
        background: #3498db;
        color: white;
        border: none;
        padding: 0.5rem 1rem;
        border-radius: 4px;
        cursor: pointer;
        margin-right: 0.5rem;
    }
    
    .batch-toggle.active {
        background: #2980b9;
    }
    
    .batch-import-btn {
        background: #27ae60;
        color: white;
        border: none;
        padding: 0.75rem 1.5rem;
        border-radius: 4px;
        cursor: pointer;
        font-weight: 600;
    }
    
    .batch-import-btn:disabled {
        background: #95a5a6;
        cursor: not-allowed;
    }
    
    .template-link {
        color: #3498db;
        text-decoration: none;
        margin-left: 1rem;
    }
    
    .template-link:hover {
        text-decoration: underline;
    }
    
    .import-result {
        margin-top: 1.5rem;
        padding: 1rem;
        border-radius: 4px;
    }
    
    .import-result.success {
        background: #d4edda;
        border: 1px solid #c3e6cb;
        color: #155724;
    }
    
    .import-result.error {
        background: #f8d7da;
        border: 1px solid #f5c6cb;
        color: #721c24;
    }
    
    .error-list {
        max-height: 300px;
        overflow-y: auto;
        margin-top: 1rem;
        padding: 1rem;
        background: white;
        border-radius: 4px;
    }
    
    .error-item {
        padding: 0.5rem;
        margin-bottom: 0.5rem;
        background: #fff3cd;
        border-left: 3px solid #ffc107;
        font-size: 0.9rem;
    }
    
    .progress-bar {
        width: 100%;
        height: 30px;
        background: #e0e0e0;
        border-radius: 15px;
        overflow: hidden;
        margin: 1rem 0;
    }
    
    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        transition: width 0.3s;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: 600;
    }
</style>
{% endblock %}

{% block content %}
<h2 style="margin-bottom:1.5rem;">数据导入</h2>

<!-- 学生+成绩 合并导入 -->
<div class="card import-section">
    <div class="card-title">
        合并导入 学生+成绩 数据
        <a href="#" class="template-link" onclick="downloadTemplate('student_grades'); return false;">下载模板</a>
    </div>
    <div class="upload-area" id="student_grades-upload" onclick="document.getElementById('student_grades-file').click()">
        <div class="upload-icon">📤</div>
        <p>点击或拖拽文件到此处上传</p>
        <p style="color:#7f8c8d;font-size:0.9rem;">支持 CSV 和 Excel 格式</p>
        <input type="file" id="student_grades-file" class="file-input" accept=".csv,.xlsx,.xls" onchange="handleFileSelect('student_grades', this.files)">
        <input type="file" id="student_grades-file-batch" class="file-input" multiple accept=".csv,.xlsx,.xls" onchange="handleBatchFileSelect('student_grades', this.files)" style="display:none;">
    </div>
    
    <!-- 批量导入控制 -->
    <div class="batch-controls">
        <button type="button" class="batch-toggle" id="student_grades-batch-toggle" onclick="toggleBatchMode('student_grades')">🔄 切换到批量模式</button>
        <button type="button" class="batch-import-btn" id="student_grades-batch-import" onclick="startBatchImport('student_grades')" style="display:none;" disabled>📤 开始批量导入</button>
    </div>
    
    <!-- 文件列表 -->
    <div id="student_grades-file-list" class="file-list" style="display:none;">
        <h4>📁 选中的文件：</h4>
        <div id="student_grades-files"></div>
    </div>
    
    <div id="student_grades-result"></div>
    <p style="margin-top:0.5rem;color:#7f8c8d;font-size:0.9rem;">说明：若学生不存在将自动创建；若成绩存在则更新。</p>
</div>

<!-- 教师数据导入 -->
<div class="card import-section">
    <div class="card-title">
        导入教师数据
        <a href="#" class="template-link" onclick="downloadTemplate('teachers'); return false;">下载模板</a>
    </div>
    
    <div class="upload-area" id="teachers-upload" onclick="document.getElementById('teachers-file').click()">
        <div class="upload-icon">📤</div>
        <p>点击或拖拽文件到此处上传</p>
        <p style="color:#7f8c8d;font-size:0.9rem;">支持 CSV 和 Excel 格式</p>
        <input type="file" id="teachers-file" class="file-input" accept=".csv,.xlsx,.xls" onchange="handleFileSelect('teachers', this.files)">
        <input type="file" id="teachers-file-batch" class="file-input" multiple accept=".csv,.xlsx,.xls" onchange="handleBatchFileSelect('teachers', this.files)" style="display:none;">
    </div>
    
    <!-- 批量导入控制 -->
    <div class="batch-controls">
        <button type="button" class="batch-toggle" id="teachers-batch-toggle" onclick="toggleBatchMode('teachers')">🔄 切换到批量模式</button>
        <button type="button" class="batch-import-btn" id="teachers-batch-import" onclick="startBatchImport('teachers')" style="display:none;" disabled>📤 开始批量导入</button>
    </div>
    
    <!-- 文件列表 -->
    <div id="teachers-file-list" class="file-list" style="display:none;">
        <h4>📁 选中的文件：</h4>
        <div id="teachers-files"></div>
    </div>
    
    <div id="teachers-result"></div>
</div>

<!-- 课程数据导入 -->
<div class="card import-section">
    <div class="card-title">
        导入课程数据
        <a href="#" class="template-link" onclick="downloadTemplate('courses'); return false;">下载模板</a>
    </div>
    
    <div class="upload-area" id="courses-upload" onclick="document.getElementById('courses-file').click()">
        <div class="upload-icon">📤</div>
        <p>点击或拖拽文件到此处上传</p>
        <p style="color:#7f8c8d;font-size:0.9rem;">支持 CSV 和 Excel 格式</p>
        <input type="file" id="courses-file" class="file-input" accept=".csv,.xlsx,.xls" onchange="handleFileSelect('courses', this.files)">
        <input type="file" id="courses-file-batch" class="file-input" multiple accept=".csv,.xlsx,.xls" onchange="handleBatchFileSelect('courses', this.files)" style="display:none;">
    </div>
    
    <!-- 批量导入控制 -->
    <div class="batch-controls">
        <button type="button" class="batch-toggle" id="courses-batch-toggle" onclick="toggleBatchMode('courses')">🔄 切换到批量模式</button>
        <button type="button" class="batch-import-btn" id="courses-batch-import" onclick="startBatchImport('courses')" style="display:none;" disabled>📤 开始批量导入</button>
    </div>
    
    <!-- 文件列表 -->
    <div id="courses-file-list" class="file-list" style="display:none;">
        <h4>📁 选中的文件：</h4>
        <div id="courses-files"></div>
    </div>
    
    <div id="courses-result"></div>
</div>

{% endblock %}

{% block extra_js %}
<script>
    // 全局变量存储文件
    let batchFiles = {};
    let batchMode = {};
    
    // 拖拽上传支持
    function setupDragDrop(type) {
        const uploadArea = document.getElementById(`${type}-upload`);
        
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragging');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragging');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragging');
            
            if (batchMode[type]) {
                handleBatchFileSelect(type, e.dataTransfer.files);
            } else {
            handleFileSelect(type, e.dataTransfer.files);
            }
        });
    }
    
    // 切换批量模式
    function toggleBatchMode(type) {
        const uploadArea = document.getElementById(`${type}-upload`);
        const toggle = document.getElementById(`${type}-batch-toggle`);
        const fileList = document.getElementById(`${type}-file-list`);
        const batchImportBtn = document.getElementById(`${type}-batch-import`);
        const normalFile = document.getElementById(`${type}-file`);
        const batchFile = document.getElementById(`${type}-file-batch`);
        
        batchMode[type] = !batchMode[type];
        
        if (batchMode[type]) {
            uploadArea.classList.add('batch-mode');
            uploadArea.innerHTML = `
                <div class="upload-icon">📂</div>
                <p>点击或拖拽多个文件到此处上传</p>
                <p style="color:rgba(255,255,255,0.8);font-size:0.9rem;">支持 CSV 和 Excel 格式（可选择多个文件）</p>
            `;
            uploadArea.onclick = () => batchFile.click();
            
            toggle.innerHTML = '📄 切换到单文件模式';
            toggle.classList.add('active');
            fileList.style.display = 'block';
            batchImportBtn.style.display = 'inline-block';
            
            // 初始化空文件列表
            batchFiles[type] = [];
            updateFileList(type);
        } else {
            uploadArea.classList.remove('batch-mode');
            uploadArea.innerHTML = `
                <div class="upload-icon">📤</div>
                <p>点击或拖拽文件到此处上传</p>
                <p style="color:#7f8c8d;font-size:0.9rem;">支持 CSV 和 Excel 格式</p>
            `;
            uploadArea.onclick = () => normalFile.click();
            
            toggle.innerHTML = '🔄 切换到批量模式';
            toggle.classList.remove('active');
            fileList.style.display = 'none';
            batchImportBtn.style.display = 'none';
            
            // 清空结果
            document.getElementById(`${type}-result`).innerHTML = '';
        }
    }
    
    // 处理批量文件选择
    function handleBatchFileSelect(type, files) {
        if (!files || files.length === 0) return;
        
        const existingFiles = batchFiles[type] || [];
        const newFiles = Array.from(files);
        
        // 检查文件大小和类型
        const validFiles = newFiles.filter(file => {
            const maxSize = 16 * 1024 * 1024; // 16MB
            const validTypes = ['csv', 'xlsx', 'xls'];
            const fileType = file.name.split('.').pop().toLowerCase();
            
            if (file.size > maxSize) {
                showAlert(`文件 ${file.name} 超过16MB限制`, 'warning');
                return false;
            }
            
            if (!validTypes.includes(fileType)) {
                showAlert(`文件 ${file.name} 格式不支持`, 'warning');
                return false;
            }
            
            return true;
        });
        
        // 去重（基于文件名和大小）
        const uniqueFiles = validFiles.filter(newFile => {
            return !existingFiles.some(existing => 
                existing.name === newFile.name && existing.size === newFile.size
            );
        });
        
        batchFiles[type] = [...existingFiles, ...uniqueFiles];
        updateFileList(type);
        
        if (uniqueFiles.length > 0) {
            showAlert(`成功添加 ${uniqueFiles.length} 个文件`, 'success');
        }
    }
    
    // 更新文件列表显示
    function updateFileList(type) {
        const filesContainer = document.getElementById(`${type}-files`);
        const importBtn = document.getElementById(`${type}-batch-import`);
        const files = batchFiles[type] || [];
        
        if (files.length === 0) {
            filesContainer.innerHTML = '<p style="color:#7f8c8d;text-align:center;">未选择任何文件</p>';
            importBtn.disabled = true;
            return;
        }
        
        const totalSize = files.reduce((sum, file) => sum + file.size, 0);
        const formatSize = (bytes) => {
            if (bytes < 1024) return bytes + 'B';
            if (bytes < 1024 * 1024) return Math.round(bytes / 1024) + 'KB';
            return Math.round(bytes / (1024 * 1024)) + 'MB';
        };
        
        let html = `
            <div style="margin-bottom:1rem;padding:0.5rem;background:#e8f5e8;border-radius:4px;">
                <strong>📊 总计：${files.length} 个文件，${formatSize(totalSize)}</strong>
            </div>
        `;
        
        files.forEach((file, index) => {
            html += `
                <div class="file-item">
                    <div class="file-info">
                        📄 ${file.name}
                        <span class="file-size">${formatSize(file.size)}</span>
                    </div>
                    <button class="remove-file" onclick="removeFile('${type}', ${index})" title="删除文件">✕</button>
                </div>
            `;
        });
        
        filesContainer.innerHTML = html;
        importBtn.disabled = false;
    }
    
    // 删除文件
    function removeFile(type, index) {
        batchFiles[type].splice(index, 1);
        updateFileList(type);
        showAlert('文件已删除', 'info');
    }
    
    // 开始批量导入
    async function startBatchImport(type) {
        console.log('=== startBatchImport 调试信息 ===');
        console.log('Type:', type);
        console.log('batchFiles[type]:', batchFiles[type]);
        
        const files = batchFiles[type] || [];
        console.log('Files from batchFiles:', files);
        console.log('Files count:', files.length);
        
        files.forEach((file, index) => {
            console.log(`File ${index} in batchFiles:`, {
                name: file.name,
                size: file.size,
                type: file.type
            });
        });
        
        if (files.length === 0) {
            showAlert('请先选择文件', 'warning');
            return;
        }
        
        const resultDiv = document.getElementById(`${type}-result`);
        const importBtn = document.getElementById(`${type}-batch-import`);
        
        importBtn.disabled = true;
        importBtn.innerHTML = '🔄 导入中...';
        
        // 显示总体进度
        resultDiv.innerHTML = `
            <div class="import-result info">
                <h4>🚀 批量导入进行中...</h4>
                <div class="progress-bar">
                    <div class="progress-fill" style="width:0%" id="${type}-overall-progress">0%</div>
                </div>
                <div id="${type}-file-progress"></div>
            </div>
        `;
        
        try {
            const results = await processBatchImport(type, files);
            displayBatchResults(type, results);
        } catch (error) {
            resultDiv.innerHTML = `
                <div class="import-result error">
                    <h4>❌ 批量导入失败</h4>
                    <p>${error.message}</p>
                </div>
            `;
            showAlert('批量导入失败: ' + error.message, 'error');
        } finally {
            importBtn.disabled = false;
            importBtn.innerHTML = '📤 开始批量导入';
        }
    }
    
    // 处理批量导入
    async function processBatchImport(type, files) {
        console.log('=== 批量导入调试信息 ===');
        console.log('Type:', type);
        console.log('Files array:', files);
        console.log('Files count:', files.length);
        
        files.forEach((file, index) => {
            console.log(`File ${index}:`, {
                name: file.name,
                size: file.size,
                type: file.type,
                lastModified: file.lastModified
            });
        });
        
        const formData = new FormData();
        
        // 将所有文件添加到FormData
        files.forEach((file, index) => {
            console.log(`Adding file ${index} to FormData:`, file.name, file.size);
            formData.append('files[]', file);
        });
        
        console.log('FormData entries:');
        for (let pair of formData.entries()) {
            console.log(pair[0], pair[1]);
            if (pair[1] instanceof File) {
                console.log('  File details:', {
                    name: pair[1].name,
                    size: pair[1].size,
                    type: pair[1].type
                });
            }
        }
        
        const token = getToken();
        const response = await fetch(`${API_BASE}/import/batch/${type}`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`
            },
            body: formData
        });
        
        const result = await response.json();
        
        // 转换为前端期望的格式
        if (result.success) {
            return result.data.file_results || [];
        } else {
            throw new Error(result.error || '批量导入失败');
        }
    }
    
    // 导入单个文件（保留用于单文件模式）
    async function importSingleFile(type, file) {
        const formData = new FormData();
        formData.append('file', file);
        
        const token = getToken();
        const response = await fetch(`${API_BASE}/import/${type}`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`
            },
            body: formData
        });
        
        return await response.json();
    }
    
    // 显示批量导入结果
    function displayBatchResults(type, results) {
        const resultDiv = document.getElementById(`${type}-result`);
        
        const totalFiles = results.length;
        const successFiles = results.filter(r => r.success).length;
        const failFiles = totalFiles - successFiles;
        
        const totalSuccess = results.reduce((sum, r) => sum + (r.data?.success_count || 0), 0);
        const totalFail = results.reduce((sum, r) => sum + (r.data?.fail_count || 0), 0);
        
        let resultHTML = `
            <div class="import-result ${successFiles === totalFiles ? 'success' : (successFiles > 0 ? 'warning' : 'error')}">
                <h4>${successFiles === totalFiles ? '✅' : (successFiles > 0 ? '⚠️' : '❌')} 批量导入完成</h4>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin:1rem 0;">
                    <div>
                        <strong>📁 文件统计：</strong><br>
                        成功文件：${successFiles}/${totalFiles}<br>
                        失败文件：${failFiles}/${totalFiles}
                    </div>
                    <div>
                        <strong>📊 数据统计：</strong><br>
                        成功记录：${totalSuccess} 条<br>
                        失败记录：${totalFail} 条
                    </div>
                </div>
        `;
        
        if (failFiles > 0) {
            resultHTML += '<div class="error-list"><strong>失败文件详情：</strong>';
            results.filter(r => !r.success).forEach(result => {
                resultHTML += `<div class="error-item">❌ ${result.filename}: ${result.error || '未知错误'}</div>`;
            });
            resultHTML += '</div>';
        }
        
        resultHTML += '</div>';
        resultDiv.innerHTML = resultHTML;
        
        // 显示通知
        if (successFiles === totalFiles) {
            showAlert(`批量导入成功！共处理 ${totalFiles} 个文件，${totalSuccess} 条记录`, 'success');
        } else if (successFiles > 0) {
            showAlert(`部分导入成功！${successFiles}/${totalFiles} 个文件成功`, 'warning');
        } else {
            showAlert('批量导入失败！所有文件都未能成功导入', 'error');
        }
    }
    
    // 处理文件选择（单文件模式）
    async function handleFileSelect(type, files) {
        if (!files || files.length === 0) {
            return;
        }
        
        const file = files[0];
        const resultDiv = document.getElementById(`${type}-result`);
        
        // 显示进度
        resultDiv.innerHTML = `
            <div class="progress-bar">
                <div class="progress-fill" style="width:0%">上传中 0%</div>
            </div>
        `;
        
        try {
            const formData = new FormData();
            formData.append('file', file);
            
            const token = getToken();
            const response = await fetch(`${API_BASE}/import/${type}`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: formData
            });
            
            const data = await response.json();
            
            if (data.success) {
                const summary = data.data;
                let resultHTML = `
                    <div class="import-result success">
                        <h4>✅ 导入成功</h4>
                        <p>成功: ${summary.success_count} 条</p>
                        <p>失败: ${summary.fail_count} 条</p>
                `;
                
                if (summary.errors && summary.errors.length > 0) {
                    resultHTML += `
                        <div class="error-list">
                            <strong>错误详情:</strong>
                            ${summary.errors.map(err => `<div class="error-item">${err}</div>`).join('')}
                        </div>
                    `;
                }
                
                resultHTML += '</div>';
                resultDiv.innerHTML = resultHTML;
                
                showAlert('数据导入成功！', 'success');
            } else {
                // 处理失败情况，可能是 data.error 或 data.data.errors
                const summary = data.data || {};
                const errorMsg = data.error || '未知错误';
                
                let resultHTML = `
                    <div class="import-result error">
                        <h4>❌ 导入失败</h4>
                        <p>成功: ${summary.success_count || 0} 条</p>
                        <p>失败: ${summary.fail_count || 0} 条</p>
                `;
                
                if (summary.errors && summary.errors.length > 0) {
                    resultHTML += `
                        <div class="error-list">
                            <strong>错误详情:</strong>
                            ${summary.errors.map(err => `<div class="error-item">${err}</div>`).join('')}
                        </div>
                    `;
                } else if (errorMsg !== '未知错误') {
                    resultHTML += `<p>${errorMsg}</p>`;
                }
                
                resultHTML += '</div>';
                resultDiv.innerHTML = resultHTML;
                
                const firstError = (summary.errors && summary.errors.length > 0) 
                    ? summary.errors[0] 
                    : errorMsg;
                showAlert('数据导入失败: ' + firstError, 'error');
            }
            
        } catch (error) {
            resultDiv.innerHTML = `
                <div class="import-result error">
                    <h4>❌ 导入失败</h4>
                    <p>${error.message}</p>
                </div>
            `;
            showAlert('数据导入失败: ' + error.message, 'error');
        }
        
        // 清空文件输入
        document.getElementById(`${type}-file`).value = '';
    }
    
    // 下载模板
    async function downloadTemplate(type) {
        try {
            const data = await apiRequest(`/import/templates/${type}`);
            
            if (data.success) {
                const blob = new Blob([data.data.content], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = data.data.filename;
                link.click();
                
                showAlert('模板下载成功', 'success');
            }
        } catch (error) {
            showAlert('模板下载失败: ' + error.message, 'error');
        }
    }
    
    // 初始化
    window.addEventListener('DOMContentLoaded', () => {
        // 检查权限
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
        if (userInfo.role !== 'admin') {
            showAlert('权限不足', 'error');
            setTimeout(() => window.location.href = '/', 2000);
            return;
        }
        
        // 初始化批量模式状态
        batchMode = {
            'student_grades': false,
            'teachers': false,
            'courses': false
        };
        
        batchFiles = {
            'student_grades': [],
            'teachers': [],
            'courses': []
        };
        
        // 设置拖拽支持
        setupDragDrop('student_grades');
        setupDragDrop('teachers');
        setupDragDrop('courses');
    });
</script>
{% endblock %}










